% Quantile Treatment Effects and Bootstrap Inference under Covariate-Adaptive Randomization 
% Yichong Zhang, Xin Zheng
% 2020/02/14

% [Generate q0 in IPW estimation]

function q0 = myqr0(Y,T,P,k,W)
[b,idx] = sort(Y.*(1-T)+(10000+Y).*T);
b = [b,W(idx)./(1-P(idx)+eps)];
n = length(Y);
k1 = sum((1-T).*W./(1-P+eps))*k/n;
L =length(k);
q0 = zeros(1,L);
count = 0;
b(:,3) = zeros(n,1);
for i = 2:(floor(max(k1))+1)
    b(i,3) = sum(b(1:i,2));
 for l = 1:L
      if b(i,3)>=k1(l) && b(i-1,3)<k1(l)
        q0(l) = b(i,1);
        count = count+1;
      end
 end
if count == L
    break;
end
end
end

